<template>
  <body>
  <div :class="containerClass">
    <!-- Sign Up -->
    <div class="container__form container--signup">
      <el-form class="form" id="form1" :rules="rules" :model="user" ref="signUp" @keydown.enter.native="signUp">
        <h2 class="form__title">注册</h2>
        <el-form-item prop="username">
          <el-input type="text" placeholder="用户名" class="input" v-model="user.username" ref="signUpUsername"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" placeholder="密码" class="input" v-model="user.password"/>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input type="password" placeholder="确认密码" class="input" v-model="user.confirmPassword"/>
        </el-form-item>
        <el-form-item prop="email">
          <el-input type="email" placeholder="邮箱" class="input" v-model="user.email"/>
        </el-form-item>
        <el-form-item>
          <el-button class="btn" @click="signUp()">注册</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- Sign In -->
    <div class="container__form container--signin">
      <el-form class="form" id="form2" :rules="rules" :model="user" ref="signIn" @keydown.enter.native="signIn" v-if="userverificationCode">
        <h2 class="form__title">登录</h2>
        <el-form-item prop="username">
          <el-input type="text" placeholder="用户名" class="input" v-model="user.username" ref="loginUsername"/>
        </el-form-item>
        <el-form-item  prop="password" style="position: relative">
          <el-input type="password" placeholder="密码" class="input" v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item>
          <a href="#" class="link" style="margin-right: 20px" @click="PhoneYanzheng">手机登录</a>
          <a href="#" class="link">忘记密码?</a>
        </el-form-item>
        <el-form-item>
          <el-button class="btn" @click="signIn()">登录</el-button>
        </el-form-item>
      </el-form>
      <el-form class="form" id="form2" :rules="rules" :model="smsSending" ref="signIn" @keydown.enter.native="signIn" v-else>
        <h2 class="form__title">登录</h2>
        <el-form-item prop="phoneNumber">
          <el-input type="text" placeholder="手机号" class="input" v-model="smsSending.phoneNumber" />
        </el-form-item>
        <el-form-item  prop="verificationCode" style="position: relative">
          <el-input type="text" placeholder="验证码" class="input" v-model="smsSending.verificationCode"></el-input>
          <el-button class="bind_code_gain" :disabled="sendsmsDisabled" @click="sendsms">发送验证码</el-button>
        </el-form-item>
        <el-form-item>
          <a href="#" class="link" style="margin-right: 20px" @click="UserYanzheng">用户密码登录</a>
          <a href="#" class="link">忘记密码?</a>
        </el-form-item>
        <el-form-item>
          <el-button class="btn" @click="signIn()">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- Overlay -->
    <div class="container__overlay">
      <div class="overlay">
        <div class="overlay__panel overlay--left">
          <button class="btn" id="signIn" @click="signInChanged()">登录</button>
        </div>
        <div class="overlay__panel overlay--right">
          <button class="btn" id="signUp" @click="signUpChanged()">注册</button>
        </div>
      </div>
    </div>
  </div>
  <div style="position: fixed; bottom: 30px">
    <span style="text-decoration: none;color: white">DreamStudio软件开发工作室&nbsp;|&nbsp;<a href = "" style="text-decoration: none;color: white">联系我们</a></span>
  </div>
  <!--  <div><button @click="guanbi">关闭</button></div>-->
  </body>
</template>

<script>

  export default {
    name: "Login",
    data() {
      let validatePass = (rule, value, callback) => {
        if (value !== this.user.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      let checkEmail = (rule, value,callback) =>{
        const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if(this.user.email !== '' && !regEmail.test(this.user.email)) {
          callback(new Error('请输入有效的邮箱'));
        } else {
          callback()
        }
      }
      return {
        frequently:1,
        time:60,
        sendsmsDisabled:false,
        userverificationCode:true,
        phoneverificationCode:false,
        user: {
          username: null ,
          password: null ,
          confirmPassword: null,
          email: null
        },
        smsSending:{
          phoneNumber:null,
          verificationCode:null,
        },
        containerClass:'container',
        rules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, message: '长度不得低于6个字符', trigger: 'blur'}
          ],
          confirmPassword: [
            {required: true, message: '请再次输入密码', trigger: 'blur'},
            {validator: validatePass, trigger: 'blur'}
          ],
          email: [
            {required: true, message: '邮箱不能为空', trigger: 'blur'},
            {validator: checkEmail, trigger: 'blur'}
          ],
          phoneNumber:[
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {min:11,max:11, message: '请输入十一位手机号', trigger: 'blur'}
          ],
          verificationCode:[
            {required: true, message: '请输入验证码', trigger: 'blur'},
            {min:6,max:6, message: '请输入6位验证码', trigger: 'blur'}
          ]
        },
      }
    },
    methods: {
      sendsms()
      {
        if(this.smsSending.phoneNumber!=null&&/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(this.smsSending.phoneNumber))
        {
          this.api.duanxinApi.getverificationCode(this.smsSending.phoneNumber).then(res=>{
            console.log(res.data.split("!")[1]+"================================================///////////////////////>")
            if(res.data.split("!")[0]==="Success")
            {
              localStorage.setItem("ver",JSON.stringify(res.data))
              this.sendsmsDisabled=true;
              let timer=setInterval(()=>{
                this.time--;
                localStorage.setItem("time",this.time)
                if(this.time===0)
                {
                  clearInterval(timer)
                  this.sendsmsDisabled=false
                }
              },1000)
              this.$message.success('验证码发送成功,一分钟内有效')
            }else{
              this.$message.error(res.data)
              this.sendsmsDisabled=false
            }
          })

        }else
        {
          this.$message.error('请输入正确的手机号')
        }

      },
      PhoneYanzheng()
      {
        this.userverificationCode=!this.userverificationCode
      },
      UserYanzheng()
      {
        this.userverificationCode=!this.userverificationCode
      },
      signInChanged() {
        this.containerClass = 'container'
        this.$refs['loginUsername'].focus();
      },
      signUpChanged() {
        this.containerClass = 'container right-panel-active'
        this.$refs['signUpUsername'].focus();
      },

      signIn(){
        if(this.userverificationCode)
        {
          this.$refs['signIn'].validate((valid) => {
            if (valid) {
              this.api.userApi.signIn(this.user)
                      .then(res => {
                        if (res.code === '200') {
                          console.log(res)
                          console.log(res.data.data)
                          localStorage.setItem('user', JSON.stringify(res.data))
                          this.$router.push("/home")
                          this.$message.success('登录成功！')
                        }
                      }).catch(err => {
                console.log(err)
              })
            } else {
              return false;
            }
          })
        }
        else{
          this.$refs['signIn'].validate((valid) => {
            if (valid) {
              this.api.duanxinApi.signIn(this.smsSending.phoneNumber,this.smsSending.verificationCode)
                      .then(res => {
                        console.log(res)
                        console.log(typeof JSON.stringify(res.data))
                        console.log(JSON.stringify(res.data.data.token))
                        console.log(JSON.stringify(res.data.code))
                        if (res.data.code==="200") {
                          localStorage.setItem('user', JSON.stringify(res.data.data))
                          this.$router.push("/home")
                          this.$message.success('登录成功！')
                        }
                      }).catch(err => {
                console.log(err)
                this.$message.error('登录失败!')
              })
            } else {
              return false;
            }
          })
        }
      },
      // 踩了个大坑，自定义邮箱校验必须返回一个callback，少写了else callback() 怎么也执行不了，也不报错
      signUp() {
        console.log('hello')
        this.$refs['signUp'].validate(valid => {
          if (valid) {
            this.api.userApi.signUp(this.user)
                    .then(res => {
                      if (res.code === '200') {
                        this.containerClass = 'container'
                        this.$refs['loginUsername'].focus();
                        this.$message.success('注册成功！')
                      }
                    }).catch(err => {
              console.log(err)
            })
          }
          else {
            console.log(123)
            return false;
          }
        })
      }
    },
    mounted() {
      this.$refs['loginUsername'].focus();

    }
  }
</script>

<style scoped>
  .bind_code_gain{
    position: absolute;
    top: 20%;
    left: 51%;
    border: 0;
    opacity: 0.5;
    color: deepskyblue;
  }
  .bind_code_gain:hover{
    color: deepskyblue;
    background-color: white;
  }

  body{
    /* COLORS */
    --white: #e9e9e9;
    --gray: #333;
    --blue: #0367a6;
    --lightblue: #008997;

    /* RADII */
    --button-radius: 0.7rem;

    /* SIZES */
    --max-width: 758px;
    --max-height: 420px;

    font-size: 16px;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;

    align-items: center;
    background: var(--white) url("https://img.zmtc.com/2019/0815/20190815113424197.jpg") no-repeat fixed center;
    background-size: cover;
    display: grid;
    height: 100vh;
    place-items: center;
  }

  .form__title {
    font-weight: 300;
    margin: 0 0 1.25rem;
  }

  .link {
    color: var(--gray);
    font-size: 0.9rem;
    margin: 1.5rem 0;
    text-decoration: none;
  }

  .container {
    background-color: var(--white);
    border-radius: var(--button-radius);
    box-shadow: 0 0.9rem 1.7rem rgba(0, 0, 0, 0.25),
    0 0.7rem 0.7rem rgba(0, 0, 0, 0.22);
    height: var(--max-height);
    max-width: var(--max-width);
    overflow: hidden;
    position: relative;
    width: 100%;
  }

  .container__form {
    height: 100%;
    position: absolute;
    top: 0;
    transition: all 0.6s ease-in-out;
  }

  .container--signin {
    left: 0;
    width: 50%;
    z-index: 2;
  }

  .container.right-panel-active .container--signin {
    transform: translateX(100%);
  }

  .container--signup {
    left: 0;
    opacity: 0;
    width: 50%;
    z-index: 1;
  }

  .container.right-panel-active .container--signup {
    animation: show 0.6s;
    opacity: 1;
    transform: translateX(100%);
    z-index: 5;
  }

  .container__overlay {
    height: 100%;
    left: 50%;
    overflow: hidden;
    position: absolute;
    top: 0;
    transition: transform 0.6s ease-in-out;
    width: 50%;
    z-index: 100;
  }

  .container.right-panel-active .container__overlay {
    transform: translateX(-100%);
  }

  .overlay {
    background: var(--lightblue) url("https://img.zmtc.com/2019/0815/20190815113424197.jpg") no-repeat fixed center;
    background-size: cover;
    height: 100%;
    left: -100%;
    position: relative;
    transform: translateX(0);
    transition: transform 0.6s ease-in-out;
    width: 200%;
  }

  .container.right-panel-active .overlay {
    transform: translateX(50%);
  }

  .overlay__panel {
    align-items: center;
    display: flex;
    flex-direction: column;
    height: 100%;
    justify-content: center;
    position: absolute;
    text-align: center;
    top: 0;
    transform: translateX(0);
    transition: transform 0.6s ease-in-out;
    width: 50%;
  }

  .overlay--left {
    transform: translateX(-20%);
  }

  .container.right-panel-active .overlay--left {
    transform: translateX(0);
  }

  .overlay--right {
    right: 0;
    transform: translateX(0);
  }

  .container.right-panel-active .overlay--right {
    transform: translateX(20%);
  }

  .btn {
    background-color: var(--blue);
    background-image: linear-gradient(90deg, var(--blue) 0%, var(--lightblue) 74%);
    border-radius: 20px;
    border: 1px solid var(--blue);
    color: var(--white);
    cursor: pointer;
    font-size: 0.8rem;
    font-weight: bold;
    letter-spacing: 0.1rem;
    padding: 0.9rem 4rem;
    text-transform: uppercase;
    transition: transform 80ms ease-in;
  }

  .form > .btn {
    margin-top: 1.5rem;
  }

  .btn:active {
    transform: scale(0.95);
  }

  .btn:focus {
    outline: none;
  }

  .form {
    background-color: var(--white);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    padding: 0 3rem;
    height: 100%;
    text-align: center;
  }

  .input {
    /*background-color: #fff;*/
    border: none;
    /*padding: 0.9rem 0.9rem;*/
    height: 100%;
    margin: 0.5rem 0;
    width: 100%;
  }

  @keyframes show {
    0%,
    49.99% {
      opacity: 0;
      z-index: 1;
    }

    50%,
    100% {
      opacity: 1;
      z-index: 5;
    }
  }



</style>
